package com.vhall.component.service.room.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vhall.component.dao.room.AnchorRoomRelationMapper;
import com.vhall.component.entity.room.entity.AnchorRoomRelationEntity;
import com.vhall.component.entity.thirduser.ThirdUserVO;
import com.vhall.component.entity.thirduser.entity.ThirdUserEntity;
import com.vhall.component.entity.thirduser.enums.ThirdUserTypeEnum;
import com.vhall.component.framework.common.exception.BusinessException;
import com.vhall.component.service.room.AnchorRoomRelationService;
import com.vhall.component.service.thirduser.ThirdUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xing.wang
 * @description 针对表【anchor_room_relation(直播主播关联表)】的数据库操作Service实现
 * @createDate 2023-08-09 14:15:00
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AnchorRoomRelationServiceImpl extends ServiceImpl<AnchorRoomRelationMapper, AnchorRoomRelationEntity>
        implements AnchorRoomRelationService {
    private final ThirdUserService thirdUserService;

    @Override
    public void relationRoomDraftToThirdUser(Integer accountId, Integer roomDraftId, List<ThirdUserVO> anchorInfoList) {
        //非公司员工的信息处理
        handleRoomDraftNotStaffUser(accountId, roomDraftId, anchorInfoList);
        //公司内部员工的信息处理
        handleRoomDraftStaffUser(accountId, roomDraftId, anchorInfoList);
    }

    private void handleRoomDraftNotStaffUser(Integer accountId, Integer roomDraftId, List<ThirdUserVO> anchorInfoList) {
        List<ThirdUserVO> noStaffUserInfo = anchorInfoList.stream().filter(data -> Objects.equals(data.getUserType(), ThirdUserTypeEnum.NO_STAFF.getValue())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(noStaffUserInfo)) {
//            删除房间原有关联
            removeAnchorRoomDraftRelation(roomDraftId);
//            建立新的关联
            List<AnchorRoomRelationEntity> anchorRoomRelationEntities = noStaffUserInfo.stream().map(data -> {
                AnchorRoomRelationEntity temp = new AnchorRoomRelationEntity();
                temp.setAccountId(accountId);
                temp.setUserName(data.getName());
                temp.setUserCode(data.getUserCode());
                temp.setRoomDraftRecordId(roomDraftId);
                temp.setUserType(ThirdUserTypeEnum.NO_STAFF.getValue());
                temp.setAdvisorLicenseNo(data.getAdvisorLicenseNo());
                return temp;
            }).collect(Collectors.toList());
            saveBatch(anchorRoomRelationEntities);
        }
    }

    /**
     * 删除所有和当前草稿关联的主播关联
     * @param roomDraftId
     */
    private void removeAnchorRoomDraftRelation(Integer roomDraftId) {
        LambdaQueryWrapper<AnchorRoomRelationEntity> deleteAnchorRoomRelationWhere = Wrappers.lambdaQuery();
        deleteAnchorRoomRelationWhere.eq(AnchorRoomRelationEntity::getRoomDraftRecordId, roomDraftId);
        remove(deleteAnchorRoomRelationWhere);
    }

    private void handleRoomDraftStaffUser(Integer accountId, Integer roomDraftId, List<ThirdUserVO> anchorInfoList) {
        List<ThirdUserVO> staffUserInfos = anchorInfoList.stream().filter(data -> Objects.equals(data.getUserType(),ThirdUserTypeEnum.STAFF.getValue())).collect(Collectors.toList());

        List<String> staffUserCodes = staffUserInfos.stream().map(ThirdUserVO::getUserCode).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(staffUserCodes)) {
            List<ThirdUserEntity> thirdUserEntities = thirdUserService.getThirdUserEntitiesBatchSaveOrUpdate(staffUserCodes);
            Map<String, List<ThirdUserEntity>> thirdUserEntitiesMap = thirdUserEntities.stream().collect(Collectors.groupingBy(ThirdUserEntity::getUserCode));
            List<String> allUserCode = thirdUserEntities.stream().map(ThirdUserEntity::getUserCode).collect(Collectors.toList());
            if (CollUtil.isEmpty(allUserCode)) {
                throw new BusinessException(20000, "传递的三方用户账号错误", "third_user.err");
            }
            List<ThirdUserEntity> userEntities = anchorInfoList.stream().map(data -> {
                List<ThirdUserEntity> thirdUserEntities1 = thirdUserEntitiesMap.get(data.getUserCode());
                if (CollUtil.isNotEmpty(thirdUserEntities1)) {
                    return thirdUserEntities1.get(0);
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(userEntities)) {
    //            删除房间关联主播
                removeAnchorRoomDraftRelation(roomDraftId);
    //            建立新的关联
                List<AnchorRoomRelationEntity> anchorRoomRelationEntities = userEntities.stream().map(data -> {
                    AnchorRoomRelationEntity temp = new AnchorRoomRelationEntity();
                    temp.setAccountId(accountId);
                    temp.setUserName(data.getName());
                    temp.setUserCode(data.getUserCode());
                    temp.setRoomDraftRecordId(roomDraftId);
                    temp.setUserType(ThirdUserTypeEnum.STAFF.getValue());
                    temp.setAdvisorLicenseNo(data.getAdvisorLicenseNo());
                    return temp;
                }).collect(Collectors.toList());
                saveBatch(anchorRoomRelationEntities);
            }
        }
    }

    @Override
    public void relationRoomToThirdUser(Integer accountId, Integer ilId, List<ThirdUserVO> anchorInfoList) {
        //非公司员工的信息处理
        handleRoomNotStaffUser(accountId, ilId, anchorInfoList);
        //公司内部员工的信息处理
        handleRoomStaffUser(accountId, ilId, anchorInfoList);
    }

    /**
     * 国信员工处理
     * @param accountId
     * @param ilId
     * @param anchorInfoList
     */
    private void handleRoomStaffUser(Integer accountId, Integer ilId, List<ThirdUserVO> anchorInfoList) {
        List<ThirdUserVO> staffUserInfos = anchorInfoList.stream().filter(data -> Objects.equals(data.getUserType(),ThirdUserTypeEnum.STAFF.getValue())).collect(Collectors.toList());
        List<String> staffUserCodes = staffUserInfos.stream().map(ThirdUserVO::getUserCode).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(staffUserCodes)) {
            List<ThirdUserEntity> thirdUserEntities = thirdUserService.getThirdUserEntitiesBatchSaveOrUpdate(staffUserCodes);
            Map<String, List<ThirdUserEntity>> thirdUserEntitiesMap = thirdUserEntities.stream().collect(Collectors.groupingBy(ThirdUserEntity::getUserCode));
            List<String> allUserCode = thirdUserEntities.stream().map(ThirdUserEntity::getUserCode).collect(Collectors.toList());
            if (CollUtil.isEmpty(allUserCode)) {
                throw new BusinessException(20000, "传递的三方用户账号错误", "third_user.err");
            }
            List<ThirdUserEntity> userEntities = anchorInfoList.stream().map(data -> {
                List<ThirdUserEntity> thirdUserEntities1 = thirdUserEntitiesMap.get(data.getUserCode());
                if (CollUtil.isNotEmpty(thirdUserEntities1)) {
                    return thirdUserEntities1.get(0);
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(userEntities)) {
    //            删除房间关联主播
                removeAnchorRoomRelation(ilId);
    //            建立新的关联
                List<AnchorRoomRelationEntity> anchorRoomRelationEntities = userEntities.stream().map(data -> {
                    AnchorRoomRelationEntity temp = new AnchorRoomRelationEntity();
                    temp.setAccountId(accountId);
                    temp.setUserName(data.getName());
                    temp.setUserCode(data.getUserCode());
                    temp.setIlId(ilId);
                    temp.setUserType(ThirdUserTypeEnum.STAFF.getValue());
                    temp.setAdvisorLicenseNo(data.getAdvisorLicenseNo());
                    temp.setOrgCode(data.getOrgCode());
                    temp.setOrgName(data.getOrgName());
                    return temp;
                }).collect(Collectors.toList());
                saveBatch(anchorRoomRelationEntities);
            }
        }
    }

    private void removeAnchorRoomRelation(Integer ilId) {
        LambdaQueryWrapper<AnchorRoomRelationEntity> deleteAnchorRoomRelationWhere = Wrappers.lambdaQuery();
        deleteAnchorRoomRelationWhere.eq(AnchorRoomRelationEntity::getIlId, ilId);
        remove(deleteAnchorRoomRelationWhere);
    }

    /**
     * 非公司员工处理
     * @param accountId
     * @param ilId
     * @param anchorInfoList
     */
    private void handleRoomNotStaffUser(Integer accountId, Integer ilId, List<ThirdUserVO> anchorInfoList) {
        List<ThirdUserVO> noStaffUserInfo = anchorInfoList.stream().filter(data -> Objects.equals(data.getUserType(), ThirdUserTypeEnum.NO_STAFF.getValue())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(noStaffUserInfo)) {
//            删除房间原有关联
            removeAnchorRoomRelation(ilId);
//            建立新的关联
            List<AnchorRoomRelationEntity> anchorRoomRelationEntities = noStaffUserInfo.stream().map(data -> {
                AnchorRoomRelationEntity temp = new AnchorRoomRelationEntity();
                temp.setAccountId(accountId);
                temp.setUserName(data.getName());
                temp.setUserCode(data.getUserCode());
                temp.setIlId(ilId);
                temp.setUserType(ThirdUserTypeEnum.NO_STAFF.getValue());
                temp.setAdvisorLicenseNo(data.getAdvisorLicenseNo());
                return temp;
            }).collect(Collectors.toList());
            saveBatch(anchorRoomRelationEntities);
        }
    }
}




